<template>
  <view class="hot-container">
    <image class="logo" src="@/static/images/logo.png" mode="aspectFit"/>
    <view class="search-box">
      <my-search placeholderText="uni-app 自定义组件"></my-search>
    </view>
    <!-- @监听事件 -->
    <view class="tab-sticky">
      <my-tabs :tabData="tabData" :defaultIndex="currentIndex" @tabClick="onTabClick"></my-tabs>
    </view>

    <!-- list视图
     1.使用mock数据（假数据），构建List的基本结构
     2.美化数据
     3.根据tab的切换，获取真实数据
     4.渲染真实数据
     5.让list具备左右切换的能力
     6.完成list与tabs联动的能力
     -->
    <swiper class="swiper"
            :current="currentIndex"
            :style="{height:currentSwiperHeight+'px'}"
            @animationfinish="onSwiperEnd"
            @change="onSwiperChange"
    >
      <swiper-item class="swiper-item" v-for="(tabItem,tabIndex) in tabData" :key="tabIndex">
        <view>
          <!--加载动画 listData[currentIndex]-->
          <uni-load-more status="loading" v-if="isLoading"></uni-load-more>
          <block v-else>
            <hot-list-item :class="'hot-list-item-'+tabIndex"
                           v-for="(item,index) in  listData[tabIndex]"
                           :data="item"
                           :ranking="index + 1"
                           :key="index"
            ></hot-list-item>
          </block>

        </view>
      </swiper-item>


    </swiper>
  </view>
</template>

<script>
import {
  getHotTabs,
  getHotListFromTabType
} from '@/api/hot.js';

export default {
  data() {
    return {
      tabData: [],
      //激活项
      currentIndex: 0,
      isLoading: true,
      listData: {},
      //当前swiper的高度
      currentSwiperHeight: 0,
      //缓存高度的计算结果
      swiperHeightData: {},
      currentPageScrollTop: 0
    };
  },
  created() {
    this.loadHotTbas();
  },
  onPageScroll(res) {
    this.currentPageScrollTop = res.scrollTop
  },
  methods: {

    // 获取文章类型
    async loadHotTbas() {
      const res = await getHotTabs();
      this.tabData = res.data.list
      this.loadHotListFromTab()
    },
    //tab点击事件
    onTabClick(index) {
      this.currentIndex = index;
      // this.loadHotListFromTab();
    },
    //获取文章List列表
    async loadHotListFromTab() {
      // if (!this.listData[this.currentIndex]) {
      this.isLoading = true;
      const id = this.tabData[this.currentIndex].id;
      const res = await getHotListFromTabType(id);
      this.listData[this.currentIndex] = res.data.list;
      this.isLoading = false;
      setTimeout(async () => {
        //获取当前swiper的高
        this.currentSwiperHeight = await this.getCurrentSwiperHeight();
        //放入缓存
        this.swiperHeightData[this.currentIndex] = this.currentSwiperHeight
      }, 0)
      // }
    },
    //计算当前swiper高度
    getCurrentSwiperHeight() {
      return new Promise((resolve, reject) => {
        let sum = 0;
        //   1.拿到所有的item->异步
        const query = uni.createSelectorQuery().in(this);
        query.selectAll(`.hot-list-item-${this.currentIndex}`)
            .boundingClientRect(res => {
              // console.log(res);
              res.forEach((item) => {
                sum += item.height
              });
              resolve(sum)
            }).exec();
      })
    },
    //
    onSwiperChange(e) {
      if (this.currentPageScrollTop > 130) {
        //控制列表的滚动位置
        uni.pageScrollTo({scrollTop: 130})
      }
      this.currentIndex = e.detail.current;

    },
    //swiper动画完成
    onSwiperEnd() {
      //判断缓存是否存在，不存在在去获取数据
      if (!this.listData[this.currentIndex]) {
        return this.loadHotListFromTab();
      }
      //未return,则证明存在数据缓存，存在数据缓存，则同时存在height的缓存数据
      this.currentSwiperHeight = this.swiperHeightData[this.currentIndex];
    }
  }
}
</script>

<style lang="scss" scoped>
.hot-container {
  background-color: $uni-bg-color;

  .logo {
    width: 100%;
    height: 80px;
  }

  .search-box {
    padding: 0 16px;
    margin-bottom: 8px;
  }

  .tab-sticky {
    position: -webkit-sticky;
    position: sticky;
    z-index: 99;
    /* #ifndef H5 */
    top: 0;
    /* #endif */
    /* #ifdef H5 */
    top: 44px;
    /* #endif */
  }
}
</style>
